package com.lianxi.util;

import com.lianxi.exacl.world.MyIImageExtractor;
import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wjn
 * Date 2018/4/9
 *
 * @author wen
 */
public class PoiUtil4 {
    /**
     * Word 2007以上
     *
     * @param filePath 文件绝对路径
     * @return word内容
     */
    public static String readDocx(String filePath) {
        try {
            FileInputStream fis = new FileInputStream(new File(filePath));
            XWPFDocument document = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            fis.close();
            return extractor.getText();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String readDocx(InputStream fis) {
        try {
            XWPFDocument document = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            fis.close();
            return extractor.getText();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Word 97 - Word 2003
     *
     * @param filePath 文件绝对路径
     * @return word内容
     */
    public static String readDoc(String filePath) {
        try {
            FileInputStream fis = new FileInputStream(new File(filePath));
            HWPFDocument document = new HWPFDocument(fis);
            WordExtractor extractor = new WordExtractor(document);
            fis.close();
            return extractor.getText();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Word 97 - Word 2003
     *
     * @param inputStream 文件流
     * @return word内容
     */
    public static String readDoc(InputStream inputStream) {
        try {
            HWPFDocument document = new HWPFDocument(inputStream);
            WordExtractor extractor = new WordExtractor(document);
            inputStream.close();
            return extractor.getText();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }



    public static String docxToHtml2(InputStream inputStream) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //图片老路径与新路径关系
        HashMap<String, String> map = new HashMap<>();
        String strHtml="";
        try {
            XWPFDocument document = new XWPFDocument(inputStream);
            XHTMLOptions options = XHTMLOptions.create();
            // 存放图片的文件夹,存放图片的路径
            options.setExtractor(new MyIImageExtractor(map));
            // html中图片的路径
            options.URIResolver(new BasicURIResolver(""));
            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(document, out, options);
            strHtml = replaceImageSrc(new String(out.toByteArray()), map);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return strHtml;
    }


    public static String docToHtml2(InputStream inputStream){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            HWPFDocument wordDocument = new HWPFDocument(inputStream);
            org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
            //保存图片，并返回图片的相对路径
            wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
                return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(content);
            });
            wordToHtmlConverter.processDocument(wordDocument);
            org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(byteArrayOutputStream);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
        }
        String s = StringEscapeUtils.unescapeHtml4(new String(byteArrayOutputStream.toByteArray()));
        String s1 = Jsoup.parse(s).body().toString();
        return s1;
    }


    public static void main(String[] args) throws Exception {
//        docToHtml2();
//        FileUtil.writeString(docxToHtml2(),"E:\\Desktop\\chunwenben.html","utf-8");

//        FileUtil.writeString(docxToHtml2(), "E:\\Desktop\\chunwenben.html", "utf-8");

    }

    //替换图片路径
    public static String replaceImageSrc(String strHtml, Map<String, String> map) {
        Document document = Jsoup.parse(StringEscapeUtils.unescapeHtml4(strHtml));
        Elements imgElements = document.getElementsByTag("img");
        for (Element imgElement : imgElements) {
            String newsrc = map.get(imgElement.attr("src"));
            imgElement.attr("src", "data:image/jpeg;base64," + newsrc);
        }

        return document.getElementsByTag("div").toString();
    }

}
